import json

from django.contrib.auth.models import Group
from django.db.migrations import serializer
from django.http import JsonResponse, HttpResponse
from rest_framework.response import Response

from .models import User, Product, Category, Item, Cart, Address, Express, Pay, Order

from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
import logging
logging.basicConfig(level=logging.INFO)




class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        # Add custom claims
        token['id'] = user.id
        return token


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url','id','username','mobile','email','email_active']

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields =['url','name']

class CatogorySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Category
        fields =['url','id','name']
class ProductSerializer(serializers.ModelSerializer):
    comments = serializers.CharField(source='get_comment_count',read_only=True)
    class Meta:
        model = Product
        fields =['id','name','price','default_image_url','comments','category','sales','skus_id','create_time','quantity']

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields =['id','customer','product','count','selected','cart','order']

class CartSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cart
        fields =['id','customer']

class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields =['id','customer','sender','send_address','reciever','recieve_address']

class ExpressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Express
        fields =['id','name']

class PaySerializer(serializers.ModelSerializer):
    class Meta:
        model = Pay
        fields =['id','name']

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ['customer','address','express','express_cost','total','pay_method']
class LoginSerializer(TokenObtainPairSerializer):
    '''
    参考：https://blog.csdn.net/Ataoker/article/details/131785957
    '''
    class Meta:
        model = User
        fields = "__all__"
        read_only_fields = ["id"]
    # 可修改一些提示语
    default_error_messages = {
        'no_active_account': '该账号已被禁用,请与管理员联系!',
        'username_or_password_wrong':"账号或密码不正确！",

    }

    # 响应中,增加了user_info字段， 增加了token字段
    def validate(self, attrs):
        # data = super().validate(attrs)

        username = attrs['username']
        password = attrs['password']
        user = User.objects.filter(username=username).first()
        if not user:
            self.fail('username_or_password_wrong')

        # if user and not user.is_staff:  # 判断是否允许登录后台
        #     result = {
        #         "code": 400,
        #         "msg": "您没有权限登录后台！",
        #         "data": None
        #     }
        #     return result

        if user and not user.is_active:
            self.fail('no_active_account')


        if user and user.check_password(password):  # check_password() 对明文进行加密,并验证
            super().validate(attrs)
            refresh = self.get_token(user)
            r_data=dict()
            r_data['username'] = user.username
            r_data['id'] = user.id
            # 补充一个token字段
            r_data["token"] = str(refresh.access_token)

            request = self.context.get('request')
            request.user = user
            # result = r_data

            return r_data

        else:
            data = super().validate(attrs)
            self.fail('username_or_password_wrong')

